package com.etouch.security.exception;

import com.etouch.security.util.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author chenyunchang
 * @title
 * @date 2020/5/9 15:12
 * @Description:
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * @return
     * @author chenyunchang
     * @date 2020-05-12 20:08:02
     * @description 统一异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultUtils jsonErrorHandler(HttpServletRequest request, Exception e) throws Exception {
        ResultUtils result = new ResultUtils();
        if (e instanceof HttpRequestMethodNotSupportedException) {
            logger.error(e.getMessage(), e);
            return ResultUtils.error(404, "请求方式错误");
        } else if (e instanceof MissingServletRequestParameterException) {
            logger.error(e.getMessage(), e);
            return ResultUtils.error(404, "传参有误");
        } else if (e instanceof ProjectException) {
            result.setStatus(((ProjectException) e).getStatus());
            result.setMsg((e.getMessage()));
        } else {
            logger.error(e.getMessage(), e);
            result.setStatus(ExceptionEnum.SYSTEM_ERROR.getStatus());
            result.setMsg(ExceptionEnum.SYSTEM_ERROR.getMessage());
        }
        return result;
    }
}
